<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { selectAllApi, selectByNameApi, deleteGroupApi, deleteApi, insertApi, updateApi } from '@/api/course.js'
import { format } from 'date-fns'; // 用于格式化日期
import FileUploadUtil from '@/utils/fileUpload.js'; // 引入文件上传工具

// 查询条件
const searchName = ref('');

// 表格数据
const tableData = ref([]);
const multipleSelection = ref([]);
const loading = ref(false);


// 分页参数
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 对话框状态
const dialogVisible = ref(false);
const dialogTitle = ref('新增课程');
const formData = ref({
  id: null,
  courseName: '',
  videoFilename: '',
  totalDuration: '',
  image: '',
  originalPrice: '',
  currentPrice: '',
  introduction: '',
  targetAudience: '',
  learningOutcomes: '',
  subscriptionNotes: '',
  consultantId: '',
  studyCount: 0,
  favoriteCount: 0,
  reviewCount: 0,
  materialCount: 0,
  validityPeriod: '',
  publishTime: '',
  categoryId: '',
  consultantName: '',
  categoryName: '',
  sumRev: 0,
  sumFav: 0
});
const formRules = {
  courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  image: [{ required: true, message: '请输入课程图片 URL', trigger: 'blur' }],
  validityPeriod: [{ required: true, message: '请输入课程有效时间', trigger: 'blur' }],
  originalPrice: [{ required: true, message: '请输入原价', trigger: 'blur' }],
  currentPrice: [{ required: true, message: '请输入现价', trigger: 'blur' }],
  introduction: [{ required: true, message: '请输入简介', trigger: 'blur' }],
  targetAudience: [{ required: true, message: '请输入适用人群', trigger: 'blur' }],
  learningOutcomes: [{ required: true, message: '请输入学习收获', trigger: 'blur' }],
  subscriptionNotes: [{ required: true, message: '请输入订阅须知', trigger: 'blur' }],
  consultantId: [{ required: true, message: '请输入咨询师编号', trigger: 'blur' }],
};

// 数据获取
onMounted(() => {
  fetchData();
});

// 获取表格数据
const fetchData = async () => {
  try {
    //获取分页数据
    const res = await selectAllApi({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    console.log(res);
    if (res.code === 200) {
      tableData.value = res.data.list
        .filter(item => item.isDeleted === 0)
        .map(item => ({
          ...item,
          publishTime: format(item.publishTime, 'yyyy-MM-dd HH:mm:ss'),
          validityPeriod: format(item.validityPeriod, 'yyyy-MM-dd'),
          image: item.image ? `http://localhost:8080${item.image}` : '',
          videoFilename: item.videoFilename ? `http://localhost:8080${item.videoFilename}` : '' // 添加 videoFilename 拼接
        }));
      total.value = res.data.total;
    } else {
      console.error("查询失败：", res.data.msg);
    }
  } catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  }
};

// 模糊查询
const handleSearch = async () => {
  try {
    //获取分页数据
    const res = await selectByNameApi({
      name: searchName.value,
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    });
    if (res.code === 200) {
      tableData.value = res.data.list
        .filter(item => item.isDeleted === 0)
        .map(item => ({
          ...item,
          publishTime: format(item.publishTime, 'yyyy-MM-dd HH:mm:ss'),
          validityPeriod: format(item.validityPeriod, 'yyyy-MM-dd'),
          image: item.image ? `http://localhost:8080${item.image}` : '',
          videoFilename: item.videoFilename ? `http://localhost:8080${item.videoFilename}` : '' // 添加 videoFilename 拼接
        }));
      total.value = res.data.total;
      ElMessage.success('搜索成功');
    } else {
      console.error("查询失败：", res.data.msg);
    }
  } catch (error) {
    console.error("请求失败：", error.message);
    alert("网络错误，请稍后重试");
  }
};

// 多选变化
const handleSelectionChange = (val) => {
  multipleSelection.value = val.map((item) => item.id);
};

// 批量删除
const handleBatchDelete =  async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }
  try {
    await ElMessageBox.confirm("确定要删除选中的数据吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    loading.value = true;
    const courseIds = multipleSelection.value;// 假设是 [1, 2, 3]
    const res = await deleteGroupApi(courseIds);
    if (res.code === 200) {
      ElMessage.success("批量删除成功");
      await fetchData(); // 刷新数据
    } else {
      ElMessage.error(res.data.msg || "批量删除失败");
    }
  } catch(error) {
    if (error === "cancel") {
      ElMessage.info("已取消删除");
    } else {
      console.error("批量删除错误:", error);
      ElMessage.error("删除失败，请稍后重试");
    }
  } finally {
    loading.value = false;
  }
};

//单个删除
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除分类 ${row.courseName} 吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    //调用删除接口
    await deleteApi(row.id);
    ElMessage.success(`删除分类 ${row.courseName} 成功`);
    await fetchData();
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};

// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增课程';
  formData.value = {
    id: null,
    courseName: '',
    videoFilename: '',
    totalDuration: '',
    image: '',
    originalPrice: '',
    currentPrice: '',
    introduction: '',
    targetAudience: '',
    learningOutcomes: '',
    subscriptionNotes: '',
    consultantId: '',
    studyCount: 0,
    favoriteCount: 0,
    reviewCount: 0,
    materialCount: 0,
    validityPeriod: '',
    publishTime: '',
    categoryId: '',
    consultantName: '',
    categoryName: '',
    sumRev: 0,
    sumFav: 0
  };
  dialogVisible.value = true;
};

// 打开编辑对话框
const handleEdit = (row) => {
  dialogTitle.value = '编辑课程';
  formData.value = { ...row };
  dialogVisible.value = true;
};

// 提交表单（新增或编辑）
const handleSubmit = async () => {
  // 调用新增或编辑接口
  if (formData.value.id) {
    // 编辑
    await updateApi(formData.value);
    ElMessage.success(`编辑分类 ${formData.value.courseName} 成功`);
  } else {
    // 新增
    await insertApi(formData.value);
    ElMessage.success(`新增分类 ${formData.value.courseName} 成功`);
  }
  dialogVisible.value = false;
  await fetchData();
};

// 分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchData();
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  fetchData();
};

//上传处理逻辑
//上传图片
const uploadImage = async (param) => {
  try {
    const res = await FileUploadUtil.uploadFile(param.file, 'image');
    if (res.code === 200) {
      formData.value.image = res.data;
      ElMessage.success('图片上传成功')
    } else {
      ElMessage.error('图片上传失败');
    }
  } catch (error) {
    ElMessage.error('上传失败，请稍后重试', error);
  }
};
// 上传视频
const uploadVideo = async (param) => {
  try {
    const res = await FileUploadUtil.uploadFile(param.file, 'video');
    if (res.code === 200) {
      formData.value.videoFilename = res.data; // 保存视频路径
      ElMessage.success('视频上传成功');
    } else {
      ElMessage.error('视频上传失败');
    }
  } catch (error) {
    ElMessage.error('上传失败，请稍后重试', error);
  }
};

</script>

<template>
  <div class="page-content">
    <!-- 查询区域 -->
    <div class="search-bar">
      <el-input
        v-model="searchName"
        placeholder="请输入课程名称"
        clearable
        style="width: 200px; margin-right: 10px;"
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button type="success" @click="handleAdd" style="margin-left: 10px;">新增课程</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除课程</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px;"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="courseName" label="课程名称" width="120" />
      <el-table-column label="视频播放链接" width="150">
        <template #default="{ row }">
          <a :href="row.videoFilename" target="_blank" style="color: #409eff;">播放视频</a>
        </template>
      </el-table-column>
      <el-table-column prop="totalDuration" label="总时长(分钟)" width="150"/>
      <el-table-column label="课程图片" width="100">
        <template #default="{ row }">
          <el-image
            :src="row.image"
            style="width: 50px; height: 50px;"
            fit="cover"
          >
            <template #error>
              <div class="image-error">加载失败</div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="originalPrice" label="原价" width="100" />
      <el-table-column prop="currentPrice" label="现价" width="100" />
      <el-table-column prop="introduction" label="简介" width="150" />
      <el-table-column prop="targetAudience" label="适用人群" width="120" />
      <el-table-column prop="learningOutcomes" label="学习收获" width="120" />
      <el-table-column prop="subscriptionNotes" label="订阅须知" width="150" />
      <el-table-column prop="consultantId" label="咨询师编号" width="120" />
      <el-table-column prop="consultantName" label="咨询师姓名" width="120" />
      <el-table-column prop="studyCount" label="学习次数" width="100" />
      <el-table-column prop="sumRev" label="收藏量" width="100" />
      <el-table-column prop="sumFav" label="评价量" width="100" />
      <el-table-column prop="materialCount" label="课件数量" width="100" />
      <el-table-column prop="validityPeriod" label="课程有效时间" width="150" />
      <el-table-column prop="publishTime" label="上架时间" width="150" />
      <el-table-column prop="categoryId" label="分类编号" width="120" />
      <el-table-column prop="categoryName" label="分类名称" width="120" />
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button type="default" @click="handleEdit(row)">编辑课程</el-button>
          <el-button type="default" style="color: #f56c6c;" @click="handleDelete(row)">删除课程</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
      style="margin-top: 20px; justify-content: flex-end;"
      @size-change="handlePageSizeChange"
      @current-change="handlePageChange"
    />

    <!-- 对话框（新增/编辑复用） -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="() => dialogVisible = false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="formData.courseName" placeholder="请输入课程名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程视频" prop="videoFilename">
              <el-upload
                action=""
                :http-request="uploadVideo"
                :show-file-list="false"
                accept="video/mp4"
              >
                <el-button type="primary">上传视频</el-button>
              </el-upload>
              <span v-if="formData.videoFilename">{{ formData.videoFilename }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课程图片" prop="image">
              <el-upload
                action=""
                :http-request="uploadImage"
                :show-file-list="false"
                accept="image/jpeg,image/png"
              >
                <el-button type="primary">上传图片</el-button>
              </el-upload>
              <span v-if="formData.image">{{ formData.image }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总时长(分钟)" prop="totalDuration">
              <el-input v-model="formData.totalDuration" placeholder="请输入总时长" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="课件数量" prop="materialCount">
              <el-input v-model="formData.materialCount" placeholder="请输入课件数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="课程有效时间" prop="validityPeriod">
              <el-input v-model="formData.validityPeriod" placeholder="请输入有效时间（如 2025-12-31）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上架时间" prop="publishTime">
              <el-input v-model="formData.publishTime" placeholder="请输入上架时间（如 2025-12-31）" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input v-model.number="formData.originalPrice" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="现价" prop="currentPrice">
              <el-input v-model.number="formData.currentPrice" placeholder="请输入现价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="咨询师编号" prop="consultantId">
              <el-input v-model="formData.consultantId" placeholder="请输入咨询师编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类编号" prop="categoryId">
              <el-input v-model="formData.categoryId" placeholder="请输入分类编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习次数" prop="studyCount">
              <el-input v-model="formData.studyCount" placeholder="请输入学习次数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收藏量" prop="favoriteCount">
              <el-input v-model="formData.sumFav" placeholder="请输入收藏量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评价量" prop="reviewCount">
              <el-input v-model="formData.sumRev" placeholder="请输入评价量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介" prop="introduction">
          <el-input v-model="formData.introduction" type="textarea" :rows="3" placeholder="请输入简介" />
        </el-form-item>
        <el-form-item label="适用人群" prop="targetAudience">
          <el-input v-model="formData.targetAudience" type="textarea" :rows="3" placeholder="请输入适用人群" />
        </el-form-item>
        <el-form-item label="学习收获" prop="learningOutcome">
          <el-input v-model="formData.learningOutcomes" type="textarea" :rows="3" placeholder="请输入学习收获" />
        </el-form-item>
        <el-form-item label="订阅须知" prop="subscriptionNotice">
          <el-input v-model="formData.subscriptionNotes" type="textarea" :rows="3" placeholder="请输入订阅须知" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.page-content {
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.el-button {
  border-radius: 8px;
}

.el-button--primary {
  background: linear-gradient(90deg, #409eff, #79bbff);
  border: none;
}

.el-button--primary:hover {
  background: linear-gradient(90deg, #337ecc, #66aaff);
}

.el-button--success {
  background: linear-gradient(90deg, #67c23a, #95d475);
  border: none;
}

.el-button--success:hover {
  background: linear-gradient(90deg, #5daf34, #85c265);
}

.el-button--danger {
  background: linear-gradient(90deg, #f56c6c, #ff9999);
  border: none;
}

.el-button--danger:hover {
  background: linear-gradient(90deg, #e65a5a, #ff8888);
}

.el-table {
  overflow-x: auto;
}
.text-button {
  color: #606266; /* 模仿 text 样式的颜色 */
  background: none;
  border: none;
  padding: 0;
}
</style>
